package com.lemontree.core.shiro;

import com.lemontree.common.baseEnum.user.UserState;
import com.lemontree.common.utils.SHA256Util;
import com.lemontree.core.shiro.token.TokenManager;
import com.lemontree.web.entity.User;
import com.lemontree.web.service.PermissionService;
import com.lemontree.web.service.RoleService;
import com.lemontree.web.service.UserService;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Set;

/**
 * Created by lemontree on 2017/6/26.
 * 配置shiro域 realm的作用即是与数据库交互所用
 * 权限的实现就是在doGetAuthorizationInfo中将角色和对应权限塞入到对应的集合中
 * 让shiro来进行控制。
 */
public class SampleRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    PermissionService permissionService;

    public SampleRealm() {
        super();
    }

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Integer userId = TokenManager.getUserId();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 根据用户id获取用户角色，放入AuthorizationInfo
        Set<String> roles = roleService.getRolesByUserId(userId);
        info.setRoles(roles);
        // 根据用户id获取用户权限，放入AuthorizationInfo
        Set<String> permissions = permissionService.getPermissionByUserId(userId);
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        ShiroToken shiroToken = (ShiroToken) token;
        User user = userService.getUserByUserName(shiroToken.getUsername());
        if (null == user) {
            throw new AccountException("用户不存在！");
        }
        String psw = SHA256Util.getSHA256Str(shiroToken.getPswd());
        // 调用user的key对称加密进行对比
        if (!psw.equals(user.getPassword())) {
            throw new AccountException("用户密码错误！");
        }
        if (UserState.FROZEN_USER.getCode() == user.getUserState()) {
            throw new DisabledAccountException("改账号已被冻结！");
        } else {
            // 更新 登录信息
            user.setLastLoginTime(new Date());
            user.setLogincount(user.getLoginCount() + 1);
            userService.updateUser(user);
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
